import { getRoute } from '@/api/user'
import { construct } from '@aximario/json-tree'
import { setLocal } from './localStore'
import useStore from '@/store'
import layout from '@/layout/index.vue'
//
interface sonRoute {
  path: string
  component: any
  name: string
  meta: object
  hidden: boolean
}
interface parentRoute {
  path: string
  name: string
  component: any
  meta: object
  children: Array<any>
}

const modules = import.meta.glob('../pages/*/*/*.vue')
const modulesLayout = import.meta.glob('../layout/*.vue')
const getMenu = async (id: string) => {
  const { roleRoute } = useStore()
  const { data } = await getRoute({ id })
  const treeData = construct(data, {
    id: 'id',
    pid: 'parent_id',
    children: 'children',
  })
  const routes = []
  for (const privilege of treeData) {
    if (privilege.type === 'menu') {
      const route: parentRoute = {
        path: privilege.route,
        component: modulesLayout['../layout/index.vue'],
        name: privilege.name,
        meta: { title: privilege.name, icon: privilege.icon },
        children: [],
      }
      if (privilege.children && privilege.children.length > 0) {
        for (const p of privilege.children) {
          const son_route: sonRoute = {
            path: p.route,
            component: modules[`../pages${p.route}.vue`],
            name: p.name,
            meta: { title: p.name, icon: p.icon },
            hidden: p.hidden == 1,
          }
          route.children.push(son_route)
        }
      }
      routes.push(route)
    }
  }
  await setLocal('roleRoute', JSON.stringify(routes)) //存储路由到本地
  await roleRoute.saveRoute(routes)
  return routes
}

export { getMenu }
